package com.kingtone.rongji;

import java.io.Serializable;
import java.util.List;

import org.apache.http.Header;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.kingtone.rongji.adapter.CartProductAdapter;
import com.kingtone.rongji.adapter.CartProductAdapter.PriceChanged;
import com.kingtone.rongji.biz.Address;
import com.kingtone.rongji.biz.Product;
import com.kingtone.rongji.biz.User;
import com.kingtone.rongji.network.UserRequest;
import com.kingtone.rongji.tool.AppContasts;
import com.kingtone.rongji.tool.CartUtils;
import com.kingtone.rongji.tool.RongJiRestClient;
import com.kingtone.rongji.tool.RongJiUtils;
import com.kingtone.rongji.tool.SharedPreferencesUtil;
import com.kingtone.rongji.ui.ToastManager;
import com.loopj.android.http.AsyncHttpResponseHandler;

public class CartActivity extends BaseActivity implements PriceChanged,OnClickListener {

	private static final String tag = CartActivity.class.getSimpleName();
	
	private Context mContext;
	
	private CartProductAdapter mAdapter;
	
	private LinearLayout mEmptyLayout;
	private Button mGo;
	
	private ListView mListView;
	private Button accountBtn = null;
	
	private TextView mAllPrice;
	private TextView mAllCount;
	
	private LinearLayout mAddressLayout;
	
	private Button mEditAddressBtn;
	private Address defaultShipAdd = null;
	
	private SharedPreferencesUtil shared = null;
	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		this.setContentView(R.layout.activity_carts);
		this.mContext = CartActivity.this;
		
		initView();
		createDataList();
		
		boolean isLogin = false;
		if (SharedPreferencesUtil.getInstance(this).getBoolean(
				AppContasts.IS_LOGINED_KEY)) 
		{
			isLogin = true;
		}
		
		if(isLogin) {
			//获取默认收货地址对象
			getDefaultShippingAddress();
		}
		
		shared = SharedPreferencesUtil.getInstance(mContext);
		String defaultShippingId = shared.getString(AppContasts.DEFAULT_STORE_ADDRESS_SHIPPING_ID);
		if(TextUtils.isEmpty(defaultShippingId) && isLogin)
		{
			String userId = shared.getString(AppContasts.USERID_KEY);
			UserRequest loginRequest = new UserRequest();
			loginRequest.getUserInfo(userId, this);
		}
	}
	
	private void initView() {
		this.mAllPrice = (TextView) findViewById(R.id.all_price);
		this.mAllCount = (TextView) findViewById(R.id.all_count);
		this.mAddressLayout = (LinearLayout) findViewById(R.id.address_layout);
		this.mEditAddressBtn = (Button) findViewById(R.id.edit_address_btn);
		this.mEmptyLayout = (LinearLayout) findViewById(R.id.cart_empty);
		this.mGo = (Button) findViewById(R.id.go);
		
		showAddress(defaultShipAdd);
		
		this.mEditAddressBtn.setOnClickListener(this);
		this.mGo.setOnClickListener(this);
		
		((TextView) findViewById(R.id.title)).setText("购物车");
		
		findViewById(R.id.back).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
	}
	
	private void createDataList() {
		
		//CartUtils.clearCart(mContext);
		List<Product> datas = CartUtils.getAllProductsForCart(CartActivity.this);
		
		mAdapter = new CartProductAdapter(this, datas);
		mAdapter.setPriceChangedListener(this);

		mListView = (ListView) findViewById(R.id.id_products);
		mListView.setAdapter(mAdapter);
		changeAllPrice();
		
		accountBtn = (Button)findViewById(R.id.btn_account);
		accountBtn.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if(null==defaultShipAdd) {
					ToastManager.show(mContext, getString(R.string.address_confirm));
					return;
				}
				if(mAdapter.getDatas().size()<1) {
					ToastManager.show(mContext, getString(R.string.cart_confirm));
					return;
				}
				Intent intent = new Intent(CartActivity.this, OrderSummitActivity.class);
				intent.putExtra(AppContasts.CART_PRODUCT_LIST, (Serializable) mAdapter.getDatas());
				if(defaultShipAdd != null)
				{
					intent.putExtra("defaultAddress", defaultShipAdd);
				}
				startActivityForResult(intent, 201);
			}
		});
		
		if(datas.isEmpty()) {
			mEmptyLayout.setVisibility(View.VISIBLE);
			mListView.setVisibility(View.GONE);
		} else {
			mEmptyLayout.setVisibility(View.GONE);
			mListView.setVisibility(View.VISIBLE);
		}
		
	}

	@Override
	public void onPriceChanged(String pid) {
		changeAllPrice();
		
		if(mAdapter.isEmpty()) {
			mEmptyLayout.setVisibility(View.VISIBLE);
			mListView.setVisibility(View.GONE);
		} else {
			mEmptyLayout.setVisibility(View.GONE);
			mListView.setVisibility(View.VISIBLE);
		}
	}
	
	private void changeAllPrice() {
		double allPrice = 0;
		int allCount = 0;
		
		List<Product> datas = mAdapter.getDatas();
		if(null!=datas) {
			for(Product item : datas) {
				allPrice += (item.getQuantity()*item.getUnitPrice());
				allCount += item.getQuantity();
			}
		}
		
		mAllPrice.setText("总计：￥" + RongJiUtils.formatCost(allPrice));
		mAllCount.setText("(共" + allCount + "件，不含运费)");
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.edit_address_btn:
			if (!SharedPreferencesUtil.getInstance(CartActivity.this).getBoolean(
					AppContasts.IS_LOGINED_KEY)) 
			{
				Intent intent = new Intent(CartActivity.this, LoginActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(intent);
			} else {
				Intent addressIntent = new Intent(CartActivity.this, ReceiveAddressActivity.class);
				startActivityForResult(addressIntent, 201);
			}
			break;
		case R.id.go:
			Intent intent = new Intent(this, MainActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			break;
		default:
			break;
		}
	}
	
	/**
	 * 获取默认收货地址
	 */
	private void getDefaultShippingAddress()
	{
		String userId = SharedPreferencesUtil.getInstance(mContext).getString(AppContasts.USERID_KEY);
		RongJiRestClient.getShippingAddress(userId, "0", new AsyncHttpResponseHandler() {

			@Override
			public void onStart() {
				RongJiUtils.showEmptyProgress(mContext);
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
				RongJiUtils.dismissProgress();
				Log.e(tag, "Failed:code=" + arg0);
				if(null != arg3) {
					arg3.printStackTrace();
				}
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				
				RongJiUtils.dismissProgress();
				
				try {
					if(arg2 != null && !new String(arg2).equalsIgnoreCase("null"))
					{
						String result = new String(arg2);
						Gson gson = new Gson();
						JsonParser parser = new JsonParser();
						JsonArray array = parser.parse(result).getAsJsonArray();
						for(JsonElement obj:array) {
							Address object = gson.fromJson(obj, Address.class);
							if(object.IsDefault.equals("true"))
							{
								defaultShipAdd = object;
								showAddress(defaultShipAdd);
								break;
							}
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}	
			}	
		});
	}
	
	@Override
	public void onBussinessSuccess(Object obj) {
		super.onBussinessSuccess(obj);
		if(obj instanceof User)
		{
			String address = ((User)obj).getPickUpAddress();
			if(address != null && address.trim().length() > 0)
			{
				String[] stores = address.split(",");
				if(stores != null && stores.length > 0)
				{
					shared.putString(AppContasts.DEFAULT_STORE_ADDRESS_SHIPPING_ID, stores[0]);
				}
			}
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 201)
		{
			if (resultCode == RESULT_OK)
			{
				setDefaultAdd(data);
			}
		}
	}
	
	private void showAddress(Address address) {
		if(null != address) {
			mAddressLayout.setVisibility(View.VISIBLE);
			mEditAddressBtn.setText("编辑或者修改");
			
			TextView t1 = (TextView) findViewById(R.id.textView4);
			TextView t2 = (TextView) findViewById(R.id.textView3);
			TextView t3 = (TextView) findViewById(R.id.textView5);
			t1.setText(address.getShipTo() + " " + address.getCellPhone());
			t2.setText(address.getRegionAddress());
			t3.setText(address.getAddress());
		} else {
			mAddressLayout.setVisibility(View.GONE);
			mEditAddressBtn.setText("设置您的收货地址");
		}
	}
	
	/**
	 * 设置默认地址
	 */
	private void setDefaultAdd(Intent data)
	{
		if (data.hasExtra("defaultAddress"))
		{
			defaultShipAdd = (Address) data.getSerializableExtra("defaultAddress");
		}
		
		showAddress(defaultShipAdd);
	}
	
}
